package com.apkicon;

import com.apkicon.core.EnhancedApkIconExtractor;
import com.apkicon.core.MemoryOptimizationManager;
import com.apkicon.model.IconInfo;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

/**
 * 优化的APK图标提取器主程序
 * 提供高性能、高可靠性的图标提取服务
 */
public class OptimizedMain {
    
    public static void main(String[] args) {
        try {
            System.out.println("🚀 优化的APK图标提取器启动");
            System.out.println("=====================================");
            
            // 显示系统信息
            displaySystemInfo();
            
            // 解析命令行参数
            if (args.length < 1) {
                displayUsage();
                return;
            }
            
            String apkPath = args[0];
            int targetSize = args.length > 1 ? Integer.parseInt(args[1]) : 512;
            int timeoutSeconds = args.length > 2 ? Integer.parseInt(args[2]) : 30;
            boolean useNativeStyle = args.length > 3 ? Boolean.parseBoolean(args[3]) : true;
            
            // 验证参数
            if (targetSize <= 0 || targetSize > 2048) {
                System.err.println("❌ 错误: 目标尺寸必须在1-2048之间");
                return;
            }
            
            if (timeoutSeconds <= 0 || timeoutSeconds > 300) {
                System.err.println("❌ 错误: 超时时间必须在1-300秒之间");
                return;
            }
            
            // 执行图标提取
            extractIcon(apkPath, targetSize, timeoutSeconds, useNativeStyle);
            
        } catch (Exception e) {
            System.err.println("❌ 程序执行失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 清理资源
            cleanup();
        }
    }
    
    /**
     * 提取图标
     */
    private static void extractIcon(String apkPath, int targetSize, int timeoutSeconds) throws Exception {
        extractIcon(apkPath, targetSize, timeoutSeconds, true);
    }
    
    /**
     * 提取图标 - 带风格选择
     */
    private static void extractIcon(String apkPath, int targetSize, int timeoutSeconds, boolean useNativeStyle) throws Exception {
        File apkFile = new File(apkPath);
        
        System.out.println("📱 处理APK: " + apkFile.getName());
        System.out.println("📏 目标尺寸: " + targetSize + "x" + targetSize);
        System.out.println("⏱️ 超时设置: " + timeoutSeconds + "秒");
        System.out.println("🎨 渲染风格: " + (useNativeStyle ? "原生风格" : "优化风格"));
        System.out.println();
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 使用增强的提取器
            IconInfo iconInfo = EnhancedApkIconExtractor.extractIcon(apkFile, targetSize, timeoutSeconds, useNativeStyle);
            
            long processingTime = System.currentTimeMillis() - startTime;
            
            System.out.println("✅ 图标提取成功!");
            System.out.println("📊 处理时间: " + processingTime + "ms");
            System.out.println("🎨 图标类型: " + iconInfo.getIconType());
            System.out.println("📐 图标尺寸: " + iconInfo.getImage().getWidth() + "x" + iconInfo.getImage().getHeight());
            
            // 保存图标
            String outputPath = generateOutputPath(apkFile.getName(), targetSize);
            saveIcon(iconInfo.getImage(), outputPath);
            
            System.out.println("💾 图标已保存: " + outputPath);
            
        } catch (Exception e) {
            long processingTime = System.currentTimeMillis() - startTime;
            System.err.println("❌ 图标提取失败 (耗时: " + processingTime + "ms)");
            throw e;
        }
    }
    
    /**
     * 生成输出路径
     */
    private static String generateOutputPath(String apkName, int targetSize) {
        String baseName = apkName.replaceAll("\\.apk$", "");
        return baseName + "_icon_" + targetSize + ".png";
    }
    
    /**
     * 保存图标
     */
    private static void saveIcon(java.awt.image.BufferedImage image, String outputPath) throws IOException {
        File outputFile = new File(outputPath);
        ImageIO.write(image, "PNG", outputFile);
    }
    
    /**
     * 显示系统信息
     */
    private static void displaySystemInfo() {
        System.out.println("💻 系统信息:");
        System.out.println("   Java版本: " + System.getProperty("java.version"));
        System.out.println("   操作系统: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
        System.out.println("   可用内存: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + "MB");
        System.out.println("   处理器数: " + Runtime.getRuntime().availableProcessors());
        System.out.println();
    }
    
    /**
     * 显示使用说明
     */
    private static void displayUsage() {
        System.out.println("📖 使用说明:");
        System.out.println("   java -jar apk-icon-extractor.jar <APK文件路径> [目标尺寸] [超时秒数] [渲染风格]");
        System.out.println();
        System.out.println("📋 参数说明:");
        System.out.println("   APK文件路径  - 必需，要提取图标的APK文件路径");
        System.out.println("   目标尺寸    - 可选，图标尺寸 (默认: 512, 范围: 1-2048)");
        System.out.println("   超时秒数    - 可选，处理超时时间 (默认: 30, 范围: 1-300)");
        System.out.println("   渲染风格    - 可选，true=原生风格, false=优化风格 (默认: true)");
        System.out.println();
        System.out.println("💡 示例:");
        System.out.println("   java -jar apk-icon-extractor.jar app.apk");
        System.out.println("   java -jar apk-icon-extractor.jar app.apk 256");
        System.out.println("   java -jar apk-icon-extractor.jar app.apk 1024 60");
        System.out.println("   java -jar apk-icon-extractor.jar app.apk 512 30 true");
        System.out.println("   java -jar apk-icon-extractor.jar app.apk 512 30 false");
        System.out.println();
        System.out.println("🔧 优化特性:");
        System.out.println("   ✅ 高性能二进制XML解析");
        System.out.println("   ✅ 智能资源缓存机制");
        System.out.println("   ✅ 高质量图标渲染算法");
        System.out.println("   ✅ 完善的错误处理和重试机制");
        System.out.println("   ✅ 内存优化和自动清理");
        System.out.println("   ✅ 并发处理和超时控制");
        System.out.println("   ✅ Android原生风格渲染");
        System.out.println("   ✅ 双渲染风格支持");
        System.out.println();
    }
    
    /**
     * 清理资源
     */
    private static void cleanup() {
        try {
            System.out.println();
            System.out.println("🧹 清理资源...");
            
            // 显示性能统计
            System.out.println("📊 " + EnhancedApkIconExtractor.getPerformanceStats());
            System.out.println("💾 " + MemoryOptimizationManager.getMemoryStats());
            System.out.println("🗂️ " + MemoryOptimizationManager.getCacheStats());
            
            // 关闭所有资源
            EnhancedApkIconExtractor.shutdown();
            MemoryOptimizationManager.shutdown();
            
            System.out.println("✅ 资源清理完成");
            
        } catch (Exception e) {
            System.err.println("❌ 资源清理失败: " + e.getMessage());
        }
    }
}
